#!/bin/python3
# 功能说明：此脚本
#

import sys
import time
import random
import os
# 定义全局变量，对于一些手机号码，通过这里来生产号码
g_Mobile = []
g_BankCard = []
g_Identification = []
g_orderindex = []

# 写入
fdMap = {}


def csvFdMap():
    if not os.path.exists("./nebulapatch"):
        os.makedirs("./nebulapatch")
    tagfiles = ["tag_order_info.csv", "tag_phone_info.csv", "tag_card_info.csv", "tag_idcert_info.csv"]
    edgefiles = ["edge_mobile.csv", "edge_cert_no.csv", "edge_bank_card_no.csv"]
    for tag in tagfiles:
        fd = open("./{}/{}".format("nebulapatch", tag), 'w')
        fdMap[tag] = fd
    for edge in edgefiles:
        fd = open("./{}/{}".format("nebulapatch", edge), 'w')
        fdMap[edge] = fd


def csvclose():
    for k, fd in fdMap.items():
        if fd != None:
            fd.close()


def csvWrite(ctype, data):
    fd = fdMap[ctype]
    fd.write(data + "\n")
    pass


# 产生一个新的手机号码
def genNewEntity(entityType):
    global g_Mobile, g_BankCard, g_Identification
    if entityType == "Mobile":
        c = len(g_Mobile)
        g_Mobile.append(c + 1)
        return len(g_Mobile)
    if entityType == "BankCard":
        c = len(g_BankCard)
        g_BankCard.append(c + 1)
        return len(g_BankCard)
    if entityType == "Identification":
        c = len(g_Identification)
        g_Identification.append(c + 1)
        return len(g_Identification)
    return 0


def rdfEntity(entityType, id):
    out = ""
    if entityType == "BankCard":
        BankCard = "62141829{:0>8}".format(id)
        out = '<_:{}>\t<name>\t"{}"\t.'.format(BankCard, BankCard)
        out2 = '<_:{}>\t<type>\t"{}"\t.'.format(BankCard, entityType)
        print(out)
        print(out2)

    if entityType == "Identification":
        Identification = "4310231990{:0>8}".format(id)
        out = '<_:{}>\t<name>\t"{}"\t.'.format(Identification, Identification)
        out2 = '<_:{}>\t<type>\t"{}"\t.'.format(Identification, entityType)
        print(out)
        print(out2)


def rdfMobileEntity(id):
    out = ""
    Mobile = "186{:0>8}".format(id)
    out = '<_:{}>\t<name>\t"{}"\t.'.format(Mobile, Mobile)
    print(out)


def csvMobileEntity(id):
    # patch的数据 id以 5,6,7 开头做索引
    out = ""
    Mobile = "186{:0>8}".format(id)
    out = '{},{}'.format(5000000000 + id, Mobile)
    csvWrite("tag_phone_info.csv", out)


def csvEntity(entityType, id):
    if entityType == "BankCard":
        BankCard = "62141829{:0>8}".format(id)
        out = '{},{}'.format(6000000000 + id, BankCard)
        csvWrite("tag_card_info.csv", out)

    if entityType == "Identification":
        Identification = "4310231990{:0>8}".format(id)
        out = '{},{}'.format(7000000000 + id, Identification)
        csvWrite("tag_idcert_info.csv", out)


def genOrderNo():
    c = len(g_orderindex)
    g_orderindex.append(c + 1)
    return len(g_orderindex)


# 产生一个新的手机号码


def genOldRandEntity(entityType):
    s = None
    if entityType == "Mobile":
        s = g_Mobile
    if entityType == "BankCard":
        s = g_BankCard
    if entityType == "Identification":
        s = g_Identification
    ran = random.randint(0, len(s) - 1)
    return s[ran]


def gettime():
    # return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # return time.strftime("%Y%m%d%H%M%S", time.localtime())
    # unix_ts = time.time()
    # ts=datetime.datetime.fromtimestamp(unix_ts)
    # time.strftime("%Y-%m-%d %H:%M:%S", ts.localtime())
    st = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    st_uinx = time.mktime(time.strptime(st, "%Y-%m-%d %H:%M:%S"))
    return st, int(st_uinx)


class SecOrderInfo:
    def __init__(self, attrName, attrValue, flag):
        orderindex = genOrderNo()
        self.name = "ord9{:0>7}".format(orderindex)
        self.orderno = "ord9{:0>7}".format(orderindex)
        self.userid = "usr9{:0>7}".format(orderindex)
        self.status = "2"
        self.product = "PRD009"
        self.update, self.unix_ts = gettime()
        self.attrNex = []
        self.attrMap = {}

        attr = ["ApplymyMobile", "LoginMobile", "RelativeMobile", "BankCard", "Identification"]
        attrNext = []
        for k in attr:
            if attrName == k:
                self.attrMap[k] = attrValue
                continue
            # 将下一个阶段需要关联的属性值提取出来用于生成新的属性
            attrNext.append(k)
            if k in ["ApplymyMobile", "LoginMobile", "RelativeMobile"]:
                if flag == True:
                    # 产生一个新的手机号码
                    newid = genNewEntity("Mobile")
                    self.attrMap[k] = newid
                    # 新的实体
                    rdfMobileEntity(newid)
                    # nebula数据
                    csvMobileEntity(newid)

                else:
                    self.attrMap[k] = genOldRandEntity("Mobile")
            else:
                if flag == True:
                    newid = genNewEntity(k)
                    self.attrMap[k] = newid
                    rdfEntity(k, newid)
                    # nebula数据
                    csvEntity(k, newid)
                else:
                    self.attrMap[k] = genOldRandEntity(k)

        self.ApplymyMobile = "186{:0>8}".format(self.attrMap["ApplymyMobile"])
        self.LoginMobile = "186{:0>8}".format(self.attrMap["LoginMobile"])
        self.RelativeMobile = "186{:0>8}".format(self.attrMap["RelativeMobile"])
        self.BankCard = "62141829{:0>8}".format(self.attrMap["BankCard"])
        self.Identification = "4310231990{:0>8}".format(self.attrMap["Identification"])
        pass

    def Print(self):
        print("{}->name->{}".format(self.name, self.orderno))
        print("{}->orderno->{}".format(self.name, self.orderno))
        print("{}->usrid->{}".format(self.name, self.userid))
        print("{}->product->{}".format(self.name, self.product))
        print("{}->status->{}".format(self.name, self.status))
        print("{}->update->{}".format(self.name, self.update))
        print("{}->ApplymyMobile->{}".format(self.name, self.ApplymyMobile))
        print("{}->LoginMobile->{}".format(self.name, self.LoginMobile))
        print("{}->RelativeMobile->{}".format(self.name, self.RelativeMobile))
        print("{}->BankCard->{}".format(self.name, self.BankCard))
        print("{}->Identification->{}".format(self.name, self.Identification))

    def PrindRdf(self):
        print('<_:{}>\t<name>\t"{}"\t.'.format(self.name, self.name))
        print('<_:{}>\t<orderno>\t"{}"\t.'.format(self.name, self.name))
        print('<_:{}>\t<userid>\t"{}"\t.'.format(self.name, self.userid))
        print('<_:{}>\t<status>\t"{}"\t.'.format(self.name, self.status))
        print('<_:{}>\t<update>\t"{}"\t.'.format(self.name, self.update))
        print('<_:{}>\t<product>\t"{}"\t.'.format(self.name, self.product))
        print('<_:{}>\t<{}>\t<_:{}>\t.'.format(self.name, "ApplymyMobile", self.ApplymyMobile))
        print('<_:{}>\t<{}>\t<_:{}>\t.'.format(self.name, "LoginMobile", self.LoginMobile))
        print('<_:{}>\t<{}>\t<_:{}>\t.'.format(self.name, "RelativeMobile", self.RelativeMobile))
        print('<_:{}>\t<{}>\t<_:{}>\t.'.format(self.name, "BankCard", self.BankCard))
        print('<_:{}>\t<{}>\t<_:{}>\t.'.format(self.name, "Identification", self.Identification))

    def PrindCvs(self):
        orderdata = "{},{},{},{},{}".format(self.orderno[3:], self.userid, self.product, self.status, self.unix_ts)
        csvWrite("tag_order_info.csv", orderdata)

        am = "{},{},1".format(int(self.orderno[3:]), 5000000000 + self.attrMap["ApplymyMobile"])
        lm = "{},{},2".format(int(self.orderno[3:]), 5000000000 + self.attrMap["LoginMobile"])
        rm = "{},{},3".format(int(self.orderno[3:]), 5000000000 + self.attrMap["RelativeMobile"])
        card = "{},{}".format(int(self.orderno[3:]), 6000000000 + self.attrMap["BankCard"])
        idt = "{},{}".format(int(self.orderno[3:]), 7000000000 + self.attrMap["Identification"])

        csvWrite("edge_mobile.csv", am)
        csvWrite("edge_mobile.csv", lm)
        csvWrite("edge_mobile.csv", rm)
        csvWrite("edge_bank_card_no.csv", card)
        csvWrite("edge_cert_no.csv", idt)
        pass


def GenOrder():
    ord1 = SecOrderInfo("", "", True)
    ords = [ord1]

    attr = ["ApplymyMobile", "LoginMobile", "RelativeMobile", "BankCard", "Identification"]
    for a in attr:
        for i in range(5):
            ord2 = SecOrderInfo(a, ord1.attrMap[a], True)
            ords.append(ord2)
            for b in attr:
                for j in range(5):
                    flag = random.randint(0, 1)
                    if flag == 1:
                        flag = True
                    else:
                        flag = False
                    ord3 = SecOrderInfo(a, ord2.attrMap[a], flag)
                    ords.append(ord3)
        pass
    for o in ords:
        o.PrindRdf()


def GenOrderNew(max0=1, max1=10, max2=10):
    csvFdMap()
    ords = []
    topord = []
    for i in range(max0):
        ord1 = SecOrderInfo("", "", True)
        ords.append(ord1)
        topord.append(ord1)
        attr = ["ApplymyMobile", "LoginMobile", "RelativeMobile", "BankCard", "Identification"]

        # 第二层订单
        for a in attr:
            for k in range(max1):
                ord2 = SecOrderInfo(a, ord1.attrMap[a], True)
                ords.append(ord2)
                # 第三层订单
                for b in attr:
                    for j in range(max2):
                        flag = random.randint(0, 1)
                        if flag == 1:
                            flag = True
                        else:
                            flag = False
                        ord3 = SecOrderInfo(a, ord2.attrMap[a], flag)
                        ords.append(ord3)
            pass
    for o in ords:
        o.PrindRdf()
        o.PrindCvs()
    csvclose()
    for o in topord:
        print("\n## ord->{}".format(o.name))


# 这个版本不产生很多新的orderer 第三层的订单采用随机前面2层的订单号码
# 减少订单，以节省空间
def GenOrderNewV2(max0=1, max1=10, max2=10):
    csvFdMap()
    ords = []
    topord = []
    for i in range(max0):
        ord1 = SecOrderInfo("", "", True)
        ords.append(ord1)
        topord.append(ord1)
        attr = ["ApplymyMobile", "LoginMobile", "RelativeMobile", "BankCard", "Identification"]

        # 第二层订单
        for a in attr:
            for k in range(max1):
                ord2 = SecOrderInfo(a, ord1.attrMap[a], True)
                ords.append(ord2)
                # 第三层订单
                for b in attr:
                    if b == a:
                        # 相同的不再关联
                        continue
                    for j in range(max2):
                        # 1/5的概率需要重新生成
                        flag = random.randint(0, 4)
                        flag = True
                        if flag == 1:
                            flag = True
                        else:
                            flag = False
                        ord3 = SecOrderInfo(a, ord2.attrMap[a], flag)
                        ords.append(ord3)
            pass
    for o in ords:
        o.PrindRdf()
        o.PrindCvs()
    csvclose()
    for o in topord:
        print("\n## ord->{}".format(o.name))


if __name__ == '__main__':
    # GenOrder()
    if len(sys.argv) == 4:
        GenOrderNewV2(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
    if len(sys.argv) == 3:
        GenOrderNewV2(1, int(sys.argv[1]), int(sys.argv[2]))
    if len(sys.argv) == 1:
        GenOrderNewV2()
    if len(sys.argv) == 2:
        GenOrderNewV2(int(sys.argv[1]), 60, 35)
